//环境声明
import {
	appUrl,
	fileurl
} from '../config/env.js'
// import getters from '../modules/user.js'
//封装的请求方式
export function post(url, data, loading) {
	const storage_key = uni.getStorageSync('storage_key');
	if (loading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: appUrl + url, //仅为示例，并非真实接口地址。
			data: data,
			method: "POST",
			header: {
				'x-auth-token': storage_key,
				'token': storage_key
			},
			success: (res) => {
				if (res.data.code * 1 === 200) {
					resolve(res.data)
					return
				}
				reject(res.data)
			},
			fail: (res) => {
				reject(res.data)
			},
			complete: (res) => {
				uni.hideLoading();
				if (res.statusCode === 404 || res.statusCode === 500) {
					uni.showToast({
						icon: "none",
						title: "网络错误",
						position: "bottom"
					})
				}
				if (res.data.code * 1 === 300) {
					uni.showToast({
						icon: "none",
						title: res.data.msg,
						position: "bottom"
					})
				}
				if (res.data.code * 1 === 203) {
					uni.showToast({
						icon: "none",
						title: res.data.msg,
						position: "bottom"
					})
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			}
		});
	})
}
export function get(url, loading) {
	const storage_key = uni.getStorageSync('storage_key');
	if (loading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: appUrl + url, //仅为示例，并非真实接口地址。
			method: "GET",
			header: {
				// "content-type": "multipart/form-data",
				'x-auth-token': storage_key,
				'token': storage_key
			},
			success: (res) => {
				if (res.data.code * 1 === 200) {
					resolve(res.data)
					return
				}
				reject(res.data)
			},
			fail: (res) => {
				reject(res.data)
			},
			complete: (res) => {
				uni.hideLoading();
				if (res.statusCode == 404 || res.statusCode == 500) {
					uni.showToast({
						icon: "none",
						title: "网络错误",
						position: "bottom"
					})
				}
				if (res.data.code * 1 === 203 || res.data.code * 1 === 500) {
					uni.showToast({
						icon: "none",
						title: res.data.msg,
						position: "bottom"
					})
				}
			}
		});
	})
}
export function uploadFile(url, data, filename, file, type, loading) {
	if (loading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: appUrl + url, //仅为示例，并非真实接口地址。
			filePath: file,
			name: filename,
			header: {
				"content-type": "multipart/form-data",
				// 'Authorization': "Bearer" + getters.state.token
			},
			formData: data,
			// #ifdef MP-ALIPAY
			fileType: type,
			// #endif 
			success: (res) => {
				resolve(res.data)
			},
			fail: (res) => {
				reject(res.data)
			},
			complete: (res) => {
				uni.hideLoading();
				if (res.statusCode == 404 || res.statusCode == 500) {
					uni.showToast({
						icon: "none",
						title: "网络错误",
						position: "bottom"
					})
				}
			}
		});
	})
}
